//
//  UploadPhotosView.m
//  WE
//
//  Created by 要帅气的生活 on 15/11/30.
//  Copyright © 2015年 UNOHACHA. All rights reserved.
//

#import "UploadPhotosView.h"
#import "SJAvatarBrowser.h"
#import "Size.h"
@interface UploadPhotosView ()
@property (nonatomic,strong) NSMutableArray *addedPicArray;
@end
static int i = 0;
@implementation UploadPhotosView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.addedPicArray = [NSMutableArray array];
        
        _picScroller = [UIScrollView new];
        [self addSubview:_picScroller];
        
        _plusButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_picScroller addSubview:_plusButton];
        [_plusButton addTarget:self action:@selector(tianjia) forControlEvents:UIControlEventTouchUpInside];
        
        _button = [UIButton buttonWithType:UIButtonTypeSystem];
        [self addSubview:_button];
        [_button addTarget:self action:@selector(qingkong) forControlEvents:UIControlEventTouchUpInside];
        
        _imgLabel = [UILabel new];
        [_picScroller addSubview:_imgLabel];
        
        
        _imgAmount = [UILabel new];
        [self addSubview:_imgAmount];
        
        
        _picScroller.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        
        [self refreshScrollView];
        _plusButton.frame = CGRectMake(8*Width, 10*Width, 60*Width, 60*Width);
        //_plusButton.backgroundColor = [UIColor redColor];
        [_plusButton setBackgroundImage:[UIImage imageNamed:@"tianjiatupian.png"] forState:UIControlStateNormal];
        
        _imgLabel.frame = CGRectMake(78*Width, 25*Width, self.frame.size.width/2,25*Height);
        _imgLabel.font = [UIFont systemFontOfSize:15];
        _imgLabel.text = @"上传图片(最多5张)";
        
        
        _button.frame = CGRectMake(self.frame.size.width-80*Width, 70, 60, 30*Height);
        [_button setTitle:@"清空图片" forState:UIControlStateNormal];
        
        _imgAmount.frame = CGRectMake(28*Width, 70, 50*Width, 30*Height);
        _imgAmount.text = [NSString stringWithFormat:@"%ld/5",_addedPicArray.count];
        _imgAmount.font = [UIFont systemFontOfSize:15];
        _imgAmount.alpha = 0.7;
    }
    return self;
}


- (void)refreshScrollView
{
    if (_addedPicArray.count == 5) {
        CGFloat width=_addedPicArray.count*70+10;
        CGSize contentSize=CGSizeMake(width, 0);
        _plusButton.hidden = NO;
        [_picScroller setContentSize:contentSize];
        [_picScroller setContentOffset:CGPointMake(0, 0) animated:YES];
        _plusButton.hidden = YES;
    }else if (_addedPicArray.count < 4){
        if ((_addedPicArray.count+1)*70+10 > WindowWidth) {
            CGFloat width=320*Width;
            CGSize contentSize=CGSizeMake(width, 0);
            _plusButton.hidden = NO;
            [_picScroller setContentSize:contentSize];
            [_picScroller setContentOffset:CGPointMake(40, 0) animated:YES];
        }else{
            CGFloat width=320*Width;
            CGSize contentSize=CGSizeMake(width, 0);
            _plusButton.hidden = NO;
            [_picScroller setContentSize:contentSize];
            [_picScroller setContentOffset:CGPointMake(0, 0) animated:YES];
        }
    }
}
-(void)tianjia{
    
    [self showUploadImg:nil];
    
}
-(void)qingkong{
    for (UIImageView *img in _addedPicArray)
    {
        [img removeFromSuperview];
    }
    [_addedPicArray removeAllObjects];
    
    CABasicAnimation *positionAnim=[CABasicAnimation animationWithKeyPath:@"position"];
    [positionAnim setFromValue:[NSValue valueWithCGPoint:CGPointMake(_plusButton.center.x, _plusButton.center.y)]];
    [positionAnim setToValue:[NSValue valueWithCGPoint:CGPointMake(INSETS+PIC_WIDTH/2, _plusButton.center.y)]];
    [positionAnim setDelegate:self];
    [positionAnim setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [positionAnim setDuration:0.25f];
    
    [_plusButton.layer addAnimation:positionAnim forKey:nil];
    
    [_plusButton setCenter:CGPointMake(INSETS+PIC_WIDTH/2, _plusButton.center.y)];
    [UIView animateWithDuration:1 animations:^{
        
        _imgLabel.alpha = 1;
        _imgAmount.text = [NSString stringWithFormat:@"%ld/5",_addedPicArray.count];
    }];
    i = 0;
    [self refreshScrollView];
}


- (void)showUploadImg:(NSString*)param
{
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction * CameraAction = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType1 = UIImagePickerControllerSourceTypeCamera;
        picker.sourceType = sourceType1;
        
        [[self viewController] presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction * AlbumAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType2 = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.sourceType = sourceType2;
        [[self viewController] presentViewController:picker animated:YES completion:nil];
        
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"h");
        
    }];
    [alertController addAction:CameraAction];
    [alertController addAction:AlbumAction];
    [alertController addAction:cancelAction];
    
    [[self viewController] presentViewController:alertController animated:YES completion:nil];
}
//相机相册的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString * type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage * image = info[@"UIImagePickerControllerOriginalImage"];
        [picker dismissViewControllerAnimated:YES completion:nil];
        //        image = [ImageUtil reduce:image size:CGSizeMake(WindowWidth * 1.5, WindowHeight * 1.5) isAdjust:YES];
        
        
        BOOL upload = YES;
        //        if (!upload) {
        //            NSString * filePath = [ImageUtil saveImageLocal:UIImagePNGRepresentation(image)];
        //            [self uploadImageAfter:filePath];
        //            return;
        //        }
        //        if ([WebUtil isNet]) {
        [self uploadImageAfter:image];
        //
        //
        //            [[[WebUtil alloc] initWithUpload:upload_url _control:self] requestUpload:^(NSMutableDictionary * dic) {
        //
        //                [self uploadImageAfter:@""];
        //
        //            } _data:UIImagePNGRepresentation(image) _fileName:@"temp_image"];
        //        }
        //
        
    }
    
    
}
- (void)uploadImageAfter:(id)object
{
    //NSLog(@"%@",object);
    
    [self addPng];
    if (object == nil) {
        
        
    }else{
        //添加图片
        UIImageView *aImageView=[[UIImageView alloc]initWithImage:object];
        [aImageView setFrame:CGRectMake(INSETS-70, INSETS, PIC_WIDTH, PIC_HEIGHT)];
        [aImageView setUserInteractionEnabled:YES];
        UITapGestureRecognizer *doubleClick = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(PictureClick:)];
        doubleClick.numberOfTapsRequired = 1;
        [aImageView addGestureRecognizer:doubleClick];
        [_addedPicArray addObject:aImageView];
        [_picScroller addSubview:aImageView];
        _imgLabel.alpha = 0;
        _imgAmount.text = [NSString stringWithFormat:@"%ld/5",_addedPicArray.count];
        for (UIImageView *img in _addedPicArray) {
            img.tag = 80+i;
            i++;
            NSLog(@"%ld",img.tag);
            CABasicAnimation *positionAnim=[CABasicAnimation animationWithKeyPath:@"position"];
            [positionAnim setFromValue:[NSValue valueWithCGPoint:CGPointMake(img.center.x, img.center.y)]];
            [positionAnim setToValue:[NSValue valueWithCGPoint:CGPointMake(img.center.x+INSETS+PIC_WIDTH, img.center.y)]];
            [positionAnim setDelegate:self];
            [positionAnim setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
            [positionAnim setDuration:0.25f];
            [img.layer addAnimation:positionAnim forKey:nil];
            
            [img setCenter:CGPointMake(img.center.x+INSETS+PIC_WIDTH, img.center.y)];
        }
    }
    [self refreshScrollView];
    i = 0;
}
//移动添加按钮
-(void)addPng{
    CABasicAnimation *positionAnim=[CABasicAnimation animationWithKeyPath:@"position"];
    [positionAnim setFromValue:[NSValue valueWithCGPoint:CGPointMake(_plusButton.center.x, _plusButton.center.y)]];
    [positionAnim setToValue:[NSValue valueWithCGPoint:CGPointMake(_plusButton.center.x+INSETS+PIC_WIDTH, _plusButton.center.y)]];
    [positionAnim setDelegate:self];
    [positionAnim setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [positionAnim setDuration:0.25f];
    [_plusButton.layer addAnimation:positionAnim forKey:nil];
    [_plusButton setCenter:CGPointMake(_plusButton.center.x+INSETS+PIC_WIDTH, _plusButton.center.y)];
}

//如何在子视图中获取父视图的ViewController
- (UIViewController *)viewController{
    for (UIView *next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}
-(void)PictureClick:(UIPanGestureRecognizer *)panGesture
{
    //£NSLog(@"%ld",panGesture.view.tag);
    [SJAvatarBrowser showImage:_addedPicArray[panGesture.view.tag - 80]];
}
@end
